﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FastReflectionLib;
using System.Web;
using Newtonsoft.Json;
using System.Data;
using Newtonsoft.Json.Linq;
using SZHL.Data;
using SZHL.UI.AppCode;
using System.Net;
using Newtonsoft.Json.Converters;


namespace SZHL.UI.API
{
    public class QYWDManage : IWsService
    {
        public void ProcessRequest(HttpContext context, ref Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            MethodInfo methodInfo = typeof(QYWDManage).GetMethod(msg.Action.ToUpper());
            QYWDManage model = new QYWDManage();
            methodInfo.FastInvoke(model, new object[] { context, msg, P1, P2, UserInfo });

        }
        /// <summary>
        /// 添加文件夹
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void ADDFLODER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            FT_Folder Folder = JsonConvert.DeserializeObject<FT_Folder>(P1);
            if (Folder.Name == "")
            {
                Folder.Name = "新建文件夹";
            }
            if (Folder.ID == 0)
            {
                Folder.CRUser = UserInfo.User.UserName;
                Folder.CRDate = DateTime.Now;
                new FT_FolderB().Insert(Folder);
            }
            else
            {

            }
            msg.Result = Folder;

        }
        public void UPDATENAME(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strName = context.Request["Name"] ?? "";
            if (strName != "")
            {
                if (P1 == "file")
                {
                    new FT_FileB().ExsSql("UPDATE FT_File SET NAME ='" + strName + "'WHERE ID = " + P2);
                }
                else
                {
                    new FT_FolderB().ExsSql("UPDATE FT_Folder SET NAME ='" + strName + "'WHERE ID = " + P2);
                }
            }

        }


        /// <summary>
        /// 移动剪切-粘贴
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void PASTEITEM(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int PID = int.Parse(P1);
            JArray PASTEITEMS = (JArray)JsonConvert.DeserializeObject(P2);
            string strPASTEtype = PASTEITEMS[0]["PASTETYPE"].ToString();
            if (strPASTEtype == "copy")
            {
                foreach (var item in PASTEITEMS)
                {
                    int itemid = int.Parse(item["ID"].ToString());
                    if (item["type"].ToString() == "file")
                    {
                        FT_File Model = new FT_FileB().GetEntity(d => d.ID == itemid);
                        Model.FolderID = PID;
                        new FT_FileB().Insert(Model);
                    }
                    else
                    {
                        new FT_FolderB().CopyFloderTree(itemid, PID);

                    }
                }
            }
            else
            {
                foreach (var item in PASTEITEMS)
                {
                    int itemid = int.Parse(item["ID"].ToString());

                    if (item["type"].ToString() == "file")
                    {
                        FT_File Model = new FT_FileB().GetEntity(d => d.ID == itemid);
                        Model.FolderID = PID;
                        new FT_FileB().Update(Model);
                    }
                    else
                    {
                        FT_Folder Model = new FT_FolderB().GetEntity(d => d.ID == itemid);
                        Model.PFolderID = PID;
                        new FT_FolderB().Update(Model);
                    }
                }
            }



        }
        public void DELFLODER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JArray DELITEM = (JArray)JsonConvert.DeserializeObject(P1);
            foreach (var item in DELITEM)
            {
                if (item["type"].ToString() == "file")
                {//删除文件
                    new FT_FileB().Delete(d => d.ID.ToString() == item["ID"].ToString());
                }
                else
                {//删除目录
                    new FT_FolderB().DelWDTree(int.Parse(item["ID"].ToString()));

                }
            }





        }
        public void ADDFILE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JArray Files = (JArray)JsonConvert.DeserializeObject(P1);
            var date = DateTime.Now;
            List<FT_File> ListData = new List<FT_File>();
            foreach (var item in Files)
            {
                int index = item["filename"].ToString().LastIndexOf('.');

                FT_File newfile = new FT_File();
                newfile.Name = item["filename"].ToString().Substring(0, index);
                newfile.FileMD5 = item["md5"].ToString();
                newfile.FileSize = item["filesize"].ToString();
                newfile.FileVersin = 0;
                newfile.CRDate = date;
                newfile.CRUser = UserInfo.User.UserName;
                newfile.FolderID = int.Parse(P2);
                newfile.FileExtendName = item["filename"].ToString().Substring(index + 1);
                ListData.Add(newfile);
            }
            foreach (FT_File item in ListData)
            {
                new FT_FileB().Insert(item);
            }
            msg.Result = ListData;
            //  msg.Result = Folder;

        }

        /// <summary>
        /// 获取文件数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">文件夹类型</param>
        /// <param name="P2">上级文件夹ID</param>
        /// <param name="UserInfo"></param>
        public void GETLISTDATA(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            //默认找出企业文件夹查看属性为空或者包含当前用户的数据
            if (P1 == "1")//企业文件夹
            {
                //默认找出企业文件夹查看属性为空或者包含当前用户的数据
                msg.Result = new FT_FolderB().GetEntities(d => d.PFolderID.ToString() == P1 && (string.IsNullOrEmpty(d.ViewAuthUsers) || d.ViewAuthUsers.Split(',').Contains(UserInfo.User.UserName)));
                msg.Result1 = new FT_FileB().GetEntities(d => d.FolderID.ToString() == P1 && (string.IsNullOrEmpty(d.ViewAuthUsers) || d.ViewAuthUsers.Split(',').Contains(UserInfo.User.UserName)));
                return;
            }
            if (P1 == "2")//个人文件夹
            {
                msg.Result = new FT_FolderB().GetEntities(d => d.PFolderID.ToString() == P1 && d.CRUser == UserInfo.User.UserName);
                msg.Result1 = new FT_FileB().GetEntities(d => d.FolderID.ToString() == P1 && d.CRUser == UserInfo.User.UserName);
                return;
            }
            msg.Result = new FT_FolderB().GetEntities(d => d.PFolderID.ToString() == P1);
            msg.Result1 = new FT_FileB().GetEntities(d => d.FolderID.ToString() == P1);


        }

        /// <summary>
        /// 搜索文件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">文件夹类型</param>
        /// <param name="P2">搜索关键字</param>
        /// <param name="UserInfo"></param>
        public void QUERYFILE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            msg.Result = new FT_FileB().GetDTByCommand("select FT_File.*,[FT_Folder].FolderType from FT_File left join [FT_Folder] on FT_File.FolderID=[FT_Folder].ID where foldertype='" + P1 + "' and( FT_File.Name like '%" + P2 + "%' or FT_File.FileExtendName like '%" + P2 + "%')");

        }



        public void GETFOLDERTREE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            List<FT_FolderB.FoldFileItem> ListID = new List<FT_FolderB.FoldFileItem>();
            msg.Result = new FT_FolderB().GetWDTREE(int.Parse(P2), ref ListID);
            msg.Result1 = ListID;
        }

        /// <summary>
        /// 添加外部分享链接
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void ADDSHARECODE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string sharecode = new CommonHelp().GenerateCheckCode(6);
            string sharepad = DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString();
            foreach (string item in P1.SplitTOList(','))
            {
                int ID = int.Parse(item.Split('|')[0]);
                string strType = item.Split('|')[1];

                if (strType == "file")//企业文件夹
                {
                    FT_File Model = new FT_FileB().GetEntity(d => d.ID == ID);
                    if (string.IsNullOrEmpty(Model.ShareCode))
                    {
                        Model.ShareCode = sharecode;
                        Model.SharePasd = sharepad;
                        new FT_FileB().Update(Model);
                    }
                }
                else
                {

                    FT_Folder Model = new FT_FolderB().GetEntity(d => d.ID == ID);
                    if (string.IsNullOrEmpty(Model.ShareCode))
                    {
                        Model.ShareCode = sharecode;
                        Model.SharePasd = sharepad;
                        new FT_FolderB().Update(Model);
                    }
                }
            }
            msg.Result = UserInfo.QYinfo.WXUrl + "/APP_QYWD_View.html?code=" + sharecode;
            msg.Result1 = sharepad;

        }
        /// <summary>
        /// 取消分享
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">类型（file:文件,folder:目录）</param>
        /// <param name="P2">ID</param>
        /// <param name="UserInfo"></param>
        public void DELSHARECODE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            foreach (string item in P1.SplitTOList(','))
            {
                int ID = int.Parse(item.Split('|')[0]);
                string strType = item.Split('|')[1];

                if (strType == "file")//
                {
                    FT_File Model = new FT_FileB().GetEntity(d => d.ID == ID);
                    Model.ShareCode = "";
                    Model.SharePasd = "";
                    new FT_FileB().Update(Model);
                }
                else
                {
                    FT_Folder Model = new FT_FolderB().GetEntity(d => d.ID == ID);
                    Model.ShareCode = "";
                    Model.SharePasd = "";
                    new FT_FolderB().Update(Model);
                }
            }
        }

        /// <summary>
        ///获取我的收藏
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void COLLECTLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strWhere = string.Format("  ','+CollectUser+','  like '%," + UserInfo.User.UserName + ",%'");
            string strSQLFLODER = string.Format(@"select * from FT_Folder  where 1=1 and  {0}   order by CRDate desc  ", strWhere);
            DataTable dtFLODER = new FT_FolderB().GetDTByCommand(strSQLFLODER);

            string strSQLFILE = string.Format(@"select  *  from FT_File  where 1=1  and  {0}   order by CRDate desc  ", strWhere);
            DataTable dtFILE = new FT_FileB().GetDTByCommand(strSQLFILE);
            msg.Result = dtFLODER;
            msg.Result1 = dtFILE;

        }
        /// <summary>
        /// 收藏目录或文档
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void COLLECTITEM(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (P1 == "file")//
            {
                FT_File Model = new FT_FileB().GetEntity(d => d.ID.ToString() == P2);
                if (string.IsNullOrEmpty(Model.CollectUser) || !Model.CollectUser.SplitTOList(',').Contains(UserInfo.User.UserName))
                {
                    Model.CollectUser = (string.IsNullOrEmpty(Model.CollectUser) ? "" : Model.CollectUser.TrimEnd(',') + ",") + UserInfo.User.UserName;
                    new FT_FileB().Update(Model);
                }
            }
            else
            {
                FT_Folder Model = new FT_FolderB().GetEntity(d => d.ID.ToString() == P2);
                if (string.IsNullOrEmpty(Model.CollectUser) || !Model.CollectUser.SplitTOList(',').Contains(UserInfo.User.UserName))
                {
                    Model.CollectUser = (string.IsNullOrEmpty(Model.CollectUser) ? "" : Model.CollectUser.TrimEnd(',') + ",") + UserInfo.User.UserName;
                    new FT_FolderB().Update(Model);
                }
            }
        }

        /// <summary>
        /// 取消收藏
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void CANCOLLECTITEM(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (P1 == "file")//
            {
                FT_File Model = new FT_FileB().GetEntity(d => d.ID.ToString() == P2);
                if (Model.CollectUser.SplitTOList(',').Contains(UserInfo.User.UserName))
                {
                    Model.CollectUser = Model.CollectUser.Replace(UserInfo.User.UserName, ",").Replace(",,", ",").TrimEnd(',');
                    new FT_FileB().Update(Model);
                }
            }
            else
            {
                FT_Folder Model = new FT_FolderB().GetEntity(d => d.ID.ToString() == P2);
                if (Model.CollectUser.SplitTOList(',').Contains(UserInfo.User.UserName))
                {
                    Model.CollectUser = Model.CollectUser.Replace(UserInfo.User.UserName, ",").Replace(",,", ",").TrimEnd(',');
                    new FT_FolderB().Update(Model);
                }
            }
        }

        /// <summary>
        /// 获取文档ITEM
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETWDITEM(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (P1 == "file")//
            {
                FT_File Model = new FT_FileB().GetEntity(d => d.ID.ToString() == P2);
                msg.Result = Model;
            }
            else
            {
                FT_Folder Model = new FT_FolderB().GetEntity(d => d.ID.ToString() == P2);
                msg.Result = Model;
            }
        }

        /// <summary>
        /// 设置权限
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void SETAUTH(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strAuthType = context.Request["authtype"] ?? "";
            string strAUTHUsers = context.Request["users"] ?? "";
            if (P1 == "file")//ViewAuthUsers
            {
                FT_File Model = new FT_FileB().GetEntity(d => d.ID.ToString() == P2);
                Model.ViewAuthUsers = strAUTHUsers;
                new FT_FileB().Update(Model);

            }
            else//FLODER
            {
                FT_Folder Model = new FT_FolderB().GetEntity(d => d.ID.ToString() == P2);

                if (strAuthType == "0")//ViewAuthUsers
                {
                    Model.ViewAuthUsers = strAUTHUsers;
                }
                if (strAuthType == "1")//DownloadAuthUsers
                {
                    Model.DownloadAuthUsers = strAUTHUsers;
                }
                if (strAuthType == "2")//UploadaAuthUsers
                {
                    Model.UploadaAuthUsers = strAUTHUsers;
                }
                new FT_FolderB().Update(Model);
            }
        }
        public void CANCELAUTH(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (P1 == "file")//ViewAuthUsers
            {
                FT_File Model = new FT_FileB().GetEntity(d => d.ID.ToString() == P2);
                Model.ViewAuthUsers = "";
                Model.DownloadAuthUsers = "";

                new FT_FileB().Update(Model);

            }
            else//FLODER
            {
                FT_Folder Model = new FT_FolderB().GetEntity(d => d.ID.ToString() == P2);
                Model.ViewAuthUsers = "";
                Model.DownloadAuthUsers = "";
                Model.UploadaAuthUsers = "";
                new FT_FolderB().Update(Model);
            }
        }

        /// <summary>
        /// 获取能够查看的内部人员共享目录
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETNBSHARELIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            // SELECT CRUser from FT_Folder WHERE ViewAuthUsers
            string strWhere = string.Format("  ','+ViewAuthUsers+','  like '%," + UserInfo.User.UserName + ",%'");
            string strSQLFLODER = string.Format(@"select * from FT_Folder  where {0} and  {1}   order by CRDate desc  ", strWhere, "CRUser='" + P1 + "'");
            DataTable dtFLODER = new FT_FolderB().GetDTByCommand(strSQLFLODER);

            string strWherefile = string.Format("  ','+FT_File.ViewAuthUsers+','  like '%," + UserInfo.User.UserName + ",%'");
            string strSQLFILE = string.Format(@"select  FT_File.*  from FT_File left join [FT_Folder] on FT_File.FolderID=[FT_Folder].ID WHERE [FT_Folder].FolderType='2'  and  FT_File.CRUser='" + P1 + "' and  {0}   order by FT_File.CRDate desc  ", strWherefile);
            DataTable dtFILE = new FT_FileB().GetDTByCommand(strSQLFILE);
            msg.Result = dtFLODER;
            msg.Result1 = dtFILE;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETNBUSERS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            // SELECT CRUser from FT_Folder WHERE ViewAuthUsers
            string strSQLFLODER = string.Format(@"SELECT DISTINCT CRUser from FT_Folder WHERE ','+ViewAuthUsers+','  like '%," + UserInfo.User.UserName + ",%'  UNION  select DISTINCT FT_File.CRUser  from FT_File left join [FT_Folder] on FT_File.FolderID=[FT_Folder].ID WHERE [FT_Folder].FolderType='2' AND ','+FT_File.ViewAuthUsers+','  like '%," + UserInfo.User.UserName + ",%' ");
            DataTable dtFLODER = new FT_FolderB().GetDTByCommand(strSQLFLODER);
            msg.Result = dtFLODER;
        }
        /// <summary>
        /// 向服务器发送压缩目录命令
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">目录ID</param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void COMPRESSFOLDER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            List<FT_FolderB.FoldFileItem> ListID = new List<FT_FolderB.FoldFileItem>();
            dynamic obj = new FT_FolderB().GetWDTREE(int.Parse(P1), ref ListID);
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string Result = JsonConvert.SerializeObject(obj, Formatting.Indented, timeConverter).Replace("null", "\"\"");

            Dictionary<String, String> DATA = new Dictionary<String, String>();
            DATA.Add("data", Result);
            HttpWebResponse Data = CommonHelp.CreatePostHttpResponse("http://122.114.116.79:9000/document/zipfolder", DATA, 0, "", null);
            string strData = CommonHelp.GetResponseString(Data);
            msg.Result = strData;
        }



        #region 获取应用附件列表
        /// <summary>
        /// 获取附件列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">附件Id，多个以逗号隔开</param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETFILESLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            string[] fileIds = P1.Split(',');
            msg.Result = new FT_FileB().GetEntities(d => fileIds.Contains(d.ID.ToString()));
        }
        #endregion



    }
}